import React, { useState, useEffect } from 'react';
import {
  Container, Typography, Box, Tabs, Tab, TextField, Button, List, ListItem, ListItemText,
  ListItemSecondaryAction, IconButton, Accordion, AccordionSummary, AccordionDetails,
  MenuItem, Snackbar, Alert, CircularProgress, Dialog, DialogActions, DialogContent,
  DialogContentText, DialogTitle, InputAdornment
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import SearchIcon from '@mui/icons-material/Search';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { createFeedback, getUserFeedback, deleteFeedback, updateFeedback, searchFeedback } from '@/apis/feedback';

const CustomerServicePage = () => {
  const [tabValue, setTabValue] = useState(0);
  const [chatMessages, setChatMessages] = useState([]);
  const [chatInput, setChatInput] = useState('');
  const [feedback, setFeedback] = useState({ feedbackType: '', feedbackContent: '' });
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const [userFeedbacks, setUserFeedbacks] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [feedbackToDelete, setFeedbackToDelete] = useState(null);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [feedbackToEdit, setFeedbackToEdit] = useState(null);
  const [searchKeyword, setSearchKeyword] = useState('');

  useEffect(() => {
    fetchUserFeedbacks();
  }, []);

  const fetchUserFeedbacks = async () => {
    setIsLoading(true);
    try {
      const response = await getUserFeedback();
      console.log('User feedbacks:', response);
      setUserFeedbacks(Array.isArray(response) ? response : []);
    } catch (error) {
      console.error('获取用户反馈失败:', error);
      setSnackbar({ open: true, message: '获取反馈失败', severity: 'error' });
      setUserFeedbacks([]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
  };

  const handleChatSend = () => {
    if (chatInput.trim()) {
      setChatMessages([...chatMessages, { text: chatInput, sender: 'user' }]);
      setChatInput('');
      setTimeout(() => {
        setChatMessages(prev => [...prev, { text: '谢谢您的咨询，我们会尽快处理您的问题。', sender: 'support' }]);
      }, 1000);
    }
  };

  const handleFeedbackSubmit = async (e) => {
    e.preventDefault();
    try {
      const feedbackData = {
        feedbackType: feedback.feedbackType.toLowerCase(),
        feedbackContent: feedback.feedbackContent
      };
      await createFeedback(feedbackData);
      setSnackbar({ open: true, message: '感谢您的反馈！', severity: 'success' });
      setFeedback({ feedbackType: '', feedbackContent: '' });
      fetchUserFeedbacks();
    } catch (error) {
      console.error('提交反馈失败:', error);
      setSnackbar({ open: true, message: '提交反馈失败，请稍后再试。', severity: 'error' });
    }
  };

  const handleDeleteClick = (feedback) => {
    setFeedbackToDelete(feedback);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (feedbackToDelete) {
      try {
        await deleteFeedback(feedbackToDelete.id);
        setSnackbar({ open: true, message: '反馈已成功删除', severity: 'success' });
        fetchUserFeedbacks();
      } catch (error) {
        console.error('删除反馈失败:', error);
        setSnackbar({ open: true, message: '删除反馈失败，请稍后再试', severity: 'error' });
      }
    }
    setDeleteDialogOpen(false);
    setFeedbackToDelete(null);
  };

  const handleDeleteCancel = () => {
    setDeleteDialogOpen(false);
    setFeedbackToDelete(null);
  };

  const handleEditClick = (feedback) => {
    setFeedbackToEdit(feedback);
    setEditDialogOpen(true);
  };

  const handleEditConfirm = async () => {
    if (feedbackToEdit) {
      try {
        const updatedFeedback = {
          feedbackType: feedbackToEdit.feedbackType.toLowerCase(),
          feedbackContent: feedbackToEdit.feedbackContent
        };
        await updateFeedback(feedbackToEdit.id, updatedFeedback);
        setSnackbar({ open: true, message: '反馈已成功更新', severity: 'success' });
        fetchUserFeedbacks();
      } catch (error) {
        console.error('更新反馈失败:', error);
        setSnackbar({ open: true, message: '更新反馈失败，请稍后再试', severity: 'error' });
      }
    }
    setEditDialogOpen(false);
    setFeedbackToEdit(null);
  };

  const handleEditCancel = () => {
    setEditDialogOpen(false);
    setFeedbackToEdit(null);
  };

  const handleSearch = async () => {
    if (searchKeyword.trim()) {
      setIsLoading(true);
      try {
        const response = await searchFeedback(searchKeyword);
        console.log(response);
        setUserFeedbacks(Array.isArray(response) ? response : []);
      } catch (error) {
        
        console.error('搜索反馈失败:', error);
        if (error.message === '未授权，请重新登录') {
          setSnackbar({ open: true, message: '请重新登录后再试', severity: 'error' });
          // 这里可以添加重定向到登录页面的逻辑
        } else {
          setSnackbar({ open: true, message: '搜索反馈失败，请稍后再试', severity: 'error' });
        }
        setUserFeedbacks([]);
      } finally {
        setIsLoading(false);
      }
    } else {
      fetchUserFeedbacks();
    }
  };

  const faqs = [
    { question: '如何修改订单？', answer: '登录后进入"我的订单"，选择需要修改的订单，点击"修改订单"按钮进行修改。' },
    { question: '退货政策是什么？', answer: '商品签收后7天内，如果商品未使用且包装完好，可以申请退货。' },
    { question: '如何查看订单状态？', answer: '登录账户后，在"我的订单"页面可以查看所有订单的状态。' },
    { question: '如何联系客服？', answer: '您可以通过本页面的在线聊天功能直接与客服沟通，或者拨打我们的客服热线。' },
    { question: '支持哪些支付方式？', answer: '我们支持余额支付方式。' },
  ];

  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Typography variant="h4" gutterBottom>客户服务</Typography>
      <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
        <Tabs value={tabValue} onChange={handleTabChange}>
          <Tab label="在线咨询" />
          <Tab label="常见问题" />
          <Tab label="反馈建议" />
        </Tabs>
      </Box>

      {tabValue === 0 && (
        <Box>
          <List sx={{ height: 300, overflow: 'auto', bgcolor: 'background.paper', mb: 2 }}>
            {chatMessages.map((message, index) => (
              <ListItem key={index} sx={{ justifyContent: message.sender === 'user' ? 'flex-end' : 'flex-start' }}>
                <ListItemText 
                  primary={message.text} 
                  sx={{ 
                    bgcolor: message.sender === 'user' ? 'primary.light' : 'grey.200', 
                    p: 1, 
                    borderRadius: 1,
                    maxWidth: '80%'
                  }} 
                />
              </ListItem>
            ))}
          </List>
          <Box sx={{ display: 'flex' }}>
            <TextField 
              fullWidth 
              variant="outlined" 
              size="small" 
              value={chatInput} 
              onChange={(e) => setChatInput(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleChatSend()}
            />
            <Button onClick={handleChatSend} sx={{ ml: 1 }}>发送</Button>
          </Box>
        </Box>
      )}

      {tabValue === 1 && (
        <Box>
          {faqs.map((faq, index) => (
            <Accordion key={index}>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Typography>{faq.question}</Typography>
              </AccordionSummary>
              <AccordionDetails>
                <Typography>{faq.answer}</Typography>
              </AccordionDetails>
            </Accordion>
          ))}
        </Box>
      )}

      {tabValue === 2 && (
        <Box>
          <Box component="form" onSubmit={handleFeedbackSubmit}>
            <TextField
              select
              fullWidth
              label="问题类型"
              value={feedback.feedbackType}
              onChange={(e) => setFeedback({ ...feedback, feedbackType: e.target.value })}
              margin="normal"
            >
              <MenuItem value="bug">系统错误</MenuItem>
              <MenuItem value="feature">功能建议</MenuItem>
              <MenuItem value="other">其他</MenuItem>
            </TextField>
            <TextField
              fullWidth
              multiline
              rows={4}
              label="问题描述"
              value={feedback.feedbackContent}
              onChange={(e) => setFeedback({ ...feedback, feedbackContent: e.target.value })}
              margin="normal"
            />
            <Button type="submit" variant="contained" color="primary" sx={{ mt: 2 }}>
              提交反馈
            </Button>
          </Box>
          <Typography variant="h6" sx={{ mt: 4, mb: 2 }}>我的历史反馈</Typography>
          <TextField
            fullWidth
            variant="outlined"
            size="small"
            placeholder="搜索反馈"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={handleSearch}>
                    <SearchIcon />
                  </IconButton>
                </InputAdornment>
              ),
            }}
            sx={{ mb: 2 }}
          />
          {isLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center' }}>
              <CircularProgress />
            </Box>
          ) : userFeedbacks && userFeedbacks.length > 0 ? (
            <List>
              {userFeedbacks.map((item) => (
                <ListItem key={item.id}>
                  <ListItemText
                    primary={item.feedbackContent}
                    secondary={`类型: ${item.feedbackType.charAt(0).toUpperCase() + item.feedbackType.slice(1)} | 时间: ${new Date(item.createdAt).toLocaleString()}`}
                  />
                  <ListItemSecondaryAction>
                    <IconButton edge="end" aria-label="edit" onClick={() => handleEditClick(item)}>
                      <EditIcon />
                    </IconButton>
                    <IconButton edge="end" aria-label="delete" onClick={() => handleDeleteClick(item)}>
                      <DeleteIcon />
                    </IconButton>
                  </ListItemSecondaryAction>
                </ListItem>
              ))}
            </List>
          ) : (
            <Typography>暂无反馈</Typography>
          )}
        </Box>
      )}

      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert onClose={() => setSnackbar({ ...snackbar, open: false })} severity={snackbar.severity} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>

      <Dialog
        open={deleteDialogOpen}
        onClose={handleDeleteCancel}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">{"确认删除反馈"}</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">
            您确定要删除这条反馈吗？此操作不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDeleteCancel}>取消</Button>
          <Button onClick={handleDeleteConfirm} autoFocus>
            确认删除
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={editDialogOpen} onClose={handleEditCancel}>
        <DialogTitle>编辑反馈</DialogTitle>
        <DialogContent>
          <TextField
            select
            fullWidth
            label="问题类型"
            value={feedbackToEdit?.feedbackType || ''}
            onChange={(e) => setFeedbackToEdit({ ...feedbackToEdit, feedbackType: e.target.value })}
            margin="normal"
          >
            <MenuItem value="bug">系统错误</MenuItem>
            <MenuItem value="feature">功能建议</MenuItem>
            <MenuItem value="other">其他</MenuItem>
          </TextField>
          <TextField
            fullWidth
            multiline
            rows={4}
            label="问题描述"
            value={feedbackToEdit?.feedbackContent || ''}
            onChange={(e) => setFeedbackToEdit({ ...feedbackToEdit, feedbackContent: e.target.value })}
            margin="normal"
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleEditCancel}>取消</Button>
          <Button onClick={handleEditConfirm} color="primary">
            保存
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default CustomerServicePage;